package com.cjh.wechat.core.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cjh.wechat.commom.pojo.Account.LoginType;
import com.cjh.wechat.commom.pojo.User;
import com.cjh.wechat.commom.type.UserStatus;
import com.cjh.wechat.commom.util.CodeGenerate;
import com.cjh.wechat.commom.util.RandomGenerater;
import com.cjh.wechat.core.service.AccountService;
import com.cjh.wechat.core.service.UserService;

@Controller
@RequestMapping("/account")
public class AccountController
{
    @Resource
    private AccountService accountService;
    @Resource
    private UserService    userService;
    
    @ResponseBody
    @RequestMapping(value = "/addAccount", method = RequestMethod.POST)
    public String addAccount(String password, String username)
    {
        try
        {
            String uid = accountService.addAccount(password, username);
            return uid;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return "fail";
        }
    }
    
    @ResponseBody
    @RequestMapping(value = "/checkLogin", method = RequestMethod.POST)
    private String checkLogin(String id, String password, String code, Boolean saveLoginStatus, //
            HttpSession session, HttpServletResponse response)
    {
        String sessionCode = (String) session.getAttribute("code");
        LoginType loginType = accountService.checkLogin(id, password, sessionCode, code);
        switch (loginType)
        {
            case CODEERROR:
                return "CODEERROR";
            case NOEXIST:
                return "NOEXIST";
            case SESSIONEXPIRED:
                return "SESSIONEXPIRED";
            case PASSWORDERROR:
                return "PASSWORDERROR";
            case SUCCESS:
                handlerSuccess(session, response, saveLoginStatus, id);
                return "SUCCESS";
            default:
                return "UNKNOWNERROR";
        }
    }
    
    @ResponseBody
    @RequestMapping(value = "/cookieLogin", method = RequestMethod.POST)
    private String cookieLogin(HttpServletRequest request, HttpSession session)
    {
        Cookie cookie = getCookieByName(request, "LOGINSTATUS");
        if (cookie != null)
        {
            String id = cookie.getValue();
            User user = userService.findById(id);
            userService.updateStatusById(id, UserStatus.ONLINE.value);
            session.setAttribute("USERINFO", user);
            if (user != null)
            {
                return "SUCCESS";
            }
            else
            {
                return "FAIL";
            }
        }
        else
        {
            return "FAIL";
        }
        
    }
    
    @RequestMapping(value = "/code", method = RequestMethod.GET)
    public void getCode(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws IOException
    {
        String code = RandomGenerater.getNumber(4);
        session.setAttribute("code", code);
        ImageIO.write(CodeGenerate.buildImg(code), "jpeg", resp.getOutputStream());
    }
    
    private void handlerSuccess(HttpSession session, HttpServletResponse response, Boolean saveLoginStatus, String id)
    {
        User user = userService.findById(id);
        userService.updateStatusById(id, UserStatus.ONLINE.value);
        session.setAttribute("USERINFO", user);
        if (saveLoginStatus)
        {
            Cookie cookie = new Cookie("LOGINSTATUS", user.getId());
            cookie.setPath("/");
            cookie.setMaxAge(3600 * 24 * 7);
            response.addCookie(cookie);
        }
        else
        {
            System.out.println("删除cookie");
            Cookie cookie = new Cookie("LOGINSTATUS", user.getId());
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
    }
    
    private Cookie getCookieByName(HttpServletRequest request, String name)
    {
        Map<String, Cookie> cookieMap = ReadCookieMap(request);
        if (cookieMap.containsKey(name))
        {
            Cookie cookie = (Cookie) cookieMap.get(name);
            return cookie;
        }
        else
        {
            return null;
        }
    }
    
    private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request)
    {
        Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies)
        {
            for (Cookie cookie : cookies)
            {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
    
}
